package tgc.edu.yzy.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import tgc.edu.yzy.custom.CommonService;
import tgc.edu.yzy.custom.TreeDTO;
import tgc.edu.yzy.entity.Tree;
import tgc.edu.yzy.repository.TreeReoisitory;
@Service
public class TreeService extends CommonService<Tree, Integer>{
	@Autowired
	private TreeReoisitory treedao;
	public List<Tree> findByParentId(Integer id) {
		return treedao.findByParentId(id);
	}
	public List<TreeDTO> tree(Integer id) {
		List<Tree> tree = treedao.findByParentId(id);
		
		List<TreeDTO> treeDTO=new ArrayList<>();
		
		for (Iterator<Tree> iterator = tree.iterator(); iterator.hasNext();) {
			Tree trees = (Tree) iterator.next();
			
			TreeDTO treed=new TreeDTO();
			treed.setId(trees.getId());
			treed.setText(trees.getName());
			treed.setChecked(trees.getChecked());
			treed.setIconCls(trees.getIcon());
			
			//判断是否为最高级 避免出现500
			if(trees.getParent()==null) {
				treed.setParent(null);
			}else {
				treed.setParent(trees.getParent().getId());
			}
			
			//查询 节点是子节点还是父节点
			List<Tree> t=treedao.findByParentId(trees.getId());
			if(t.size()>0) {
				treed.setState("closed");
			}else {
				treed.setState("open");
			}
			//自定义的url
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("url", trees.getUrl());
			treed.setAttributes(map);
			treeDTO.add(treed);
			//treed.setState();
		}
		
		return treeDTO;
	}
	/***
	 * 递归删除所有子节点
	 * @param id
	 */
	public void treedelete(Integer id) {
		List<Tree> tree=treedao.findByParentId(id);
		for (int i = 0; i < tree.size(); i++) {
			Integer cid= tree.get(i).getId();
			treedao.delete(tree.get(i));
			treedelete(cid);
		}
		treedao.deleteById(id);
	}
	
	
}
